package base.reflection_demo.demo_02;

import base.reflection_demo.demo_01.User;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;

/**
 * 通过反射API动态的操作：通过反射获取泛型信息
 */
@Slf4j
public class GenericReflection {
    public void test01(Map<String, User> map, List<User> list){
        log.info("test01()");
    }

    public Map<Integer,User> test02(){
        log.info("test02()");
        return null;
    }

    public static void main(String[] args) throws Exception {
        //1.获得指定方法参数泛型信息
        Method method01 = GenericReflection.class.getMethod("test01", Map.class, List.class);
        method01.setAccessible(true);
        Type[] parameterTypes = method01.getGenericParameterTypes();
        for (Type parameterType : parameterTypes) {
            log.info("#{}", parameterType);
            if (parameterType instanceof ParameterizedType) {
                Type[] genericTypes = ((ParameterizedType) parameterType).getActualTypeArguments();
                for (Type genericType : genericTypes) {
                    log.info("泛型类型：{}", genericType);
                }
            }
        }

        log.info("---------------------------------------------------------");

        //2.获得指定方法返回值泛型信息
        Method method02 = GenericReflection.class.getMethod("test02", null);
        Type returnType = method02.getGenericReturnType();
        if (returnType instanceof ParameterizedType) {
            Type[] genericTypes = ((ParameterizedType) returnType).getActualTypeArguments();
            for (Type genericType : genericTypes) {
                log.info("返回值，泛型类型：{}",genericType);
            }
        }
    }

}
